import axios from "@/tools/axios-config";
import { auth } from "@/tools/auth";


export const getChapters = (courseId) => {
    return axios.get(`/chapters/?course=${courseId}`).then((res) => {
        let sortedChapters = res.data || [];
        for (let i = 0; i < sortedChapters.length - 1; i++) {
            for (let j = i + 1; j < sortedChapters.length; j++) {
                if ((sortedChapters[i].next_id === sortedChapters[j].id) && (j === i + 1)) {
                    break;
                }
                if (sortedChapters[i].next_id === sortedChapters[j].id) {
                    let tmp = sortedChapters[i + 1];
                    sortedChapters[i + 1] = sortedChapters[j];
                    sortedChapters[j] = tmp;
                    break;
                }
            }
        }
        return sortedChapters;
    });
};


/**
 * Update Chapter name.
 * @param {string} newChapterName 
 * @param {int|string} chapterId 
 * The react useMutate() callback function's param is an object.
 * 
 * 
 */
export const updateChapterNameById = ({ newChapterName, chapterId, courseId }) => {
    return axios({
        method: "patch",
        url: `/chapters/${chapterId}/`,
        data: JSON.stringify({ name: newChapterName, course: courseId }),
        headers: {
            'Content-type': 'application/json; charset=UTF-8',
            ...(auth.currentUser && {
                'Authorization': `Token ${auth.currentUser.token}`
            }),
        },
    }).then((res) => (res.data))
};

export const createChapterByCourseId = ({ chapterName, courseId, currentChapter }) => {
    return axios({
        method: "post",
        url: `/chapters/`,
        data: JSON.stringify({
            name: chapterName,
            course: courseId,
            next_id: currentChapter.next_id,
        }),
        headers: {
            'Content-type': 'application/json; charset=UTF-8',
            ...(auth.currentUser && {
                'Authorization': `Token ${auth.currentUser.token}`
            }),
        },
    }).then((res) => {
        const newChapter = res.data;
        axios({
            method: "patch",
            url: `/chapters/${currentChapter.id}/`,
            data: JSON.stringify({ next_id: newChapter.id, course: courseId }),
            headers: {
                'Content-type': 'application/json; charset=UTF-8',
                ...(auth.currentUser && {
                    'Authorization': `Token ${auth.currentUser.token}`
                }),
            },

        });
        return newChapter;
    })
}

export const getChapterText = (chapterId) => {
    return axios.get(`/chapter-texts/?chapter=${chapterId}`).then((res) => {
        // 把数组转换成单个 object
        const [data] = res.data || [];
        return data;
    });
}

export const updateChapterTextById = ({ newChapterText, chapterTextId, courseId }) => {
    return axios({
        method: "patch",
        url: `/chapter-texts/${chapterTextId}/`,
        data: JSON.stringify({
            content: newChapterText,
            course: courseId
        }),
        headers: {
            'Content-type': 'application/json; charset=UTF-8',
            ...(auth.currentUser && {
                'Authorization': `Token ${auth.currentUser.token}`
            }),
        },
    }).then((res) => (res.data))
}